import { isIOS, isApp } from './is'

export function openUrlByBrowser(url, useFormat = true, timestamp = false) {
  if (!url) {
    return
  }

  if (useFormat) {
    url = formatUrl(url)
  }

  if (isApp() && isIOS()) {
    window.yyn.registryMethod('openSafari', '2.0.5')
    window.yyn.invokeJSB('openSafari', {
      url: addTimestampToUrl(url, timestamp)
    })
  } else {
    const el = document.createElement('a')
    el.download = url.split('/').pop()
    el.href = addTimestampToUrl(url, timestamp)
    el.click()
  }

  function addTimestampToUrl(_url, _ts) {
    return _ts
      ? `${_url}${_url.includes('?') ? '&' : '?'}v=${Date.now()}`
      : _url
  }
}

function formatUrl(url) {
  return url.replace(
    /^(http|https)(:\/\/)(.+\/)([^/]+)$/g,
    (match, p1, p2, p3, p4) => {
      return p1 + p2 + p3.replace(/(\/\/)/g, '/') + encodeURIComponent(p4)
    }
  )
}
